# -*- coding: utf-8 -*-
# 模型训练：apriori-LSTM网络模型，针对时序数据的特征提取及多变量数据训练。


# tensorboard --logdir logs/fit
from math import sqrt
from matplotlib import pyplot
from numpy import clip
from Utils import data_process_ap as dp
import pandas as pd
import keras
import datetime
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM

# 全局变量定义
aimed_stl = 'A16050JJNON'
org_url = 'Data/ORDER_DATA.CSV'
new_url = 'Data/day.csv'

# apriori超参数定义
minsupport = 0.55

# lstm超参数定义
units = 128
epochs = 200
batch_size = 80


# -----------------------------------------------apriori算法-------------------------------------------------------------
# 创建大小为1的所有数据集的集合，即将所有的单项放在一个list中
def createC1(dataSet):
    C1 = []
    for data in dataSet:
        for i in data:
            if [i] not in C1:
                C1.append([i])
    return list(map(frozenset, C1))


# 计算单元素支持度，即看数据中包含此元素的数据占总数据的比例，最小支持度默认为0.55
def degreeSupport(dataSet, C1, minSupport=minsupport):
    degreeSupportList = {}  # 返回支持度字典
    dataList = []  # 返回满足最小支持度的元素列表
    itemCount = {}   # C1中元素在dataSet中出现的次数
    for data in dataSet:
        for item in C1:
            if item.issubset(data):  # 判断item是否包含在data中
                if item not in itemCount:
                    itemCount[item] = 0
                itemCount[item] += 1
    n = float(len(dataSet))
    for key in itemCount.keys():
        support = itemCount[key]/n   # 计算支持度
        if support >= minSupport:
            dataList.append(key)
        degreeSupportList[key] = support
    return dataList, degreeSupportList


# 数据合并
# 如果数据长度为n，取前n-1个元素相同的两个数据合并组成新的数据，这样不必计算所有的组合，可以省略剪枝步骤
def merge(L, k):
    n = len(L)
    dataMergeList = []
    for i in range(n-1):
        for j in range(i+1, n):
            L1 = list(L[i])[:k]
            L2 = list(L[j])[:k]
            L1.sort()
            L2.sort()
            if L1 == L2:
                dataMergeList.append(L[i] | L[j])
    return dataMergeList


def apriori(dataSet, minSupport=minsupport):
    dataSet = list(map(set, dataSet))
    C1 = createC1(dataSet)
    L1, degreeSupportList = degreeSupport(dataSet, C1, minSupport)
    L = [L1]
    k = 0
    while len(L[k]) > 1:  # 创建包含更大项集的更大列表,直到下一个大的项集为1
        Lm = merge(L[k], k)
        Lk, support = degreeSupport(dataSet, Lm, minSupport)
        L.append(Lk)
        degreeSupportList.update(support)
        k += 1
    return L, degreeSupportList, L[1]


def getBiset(steeltype):
    dataSet = dp.get_steel_day()
    L, degreeSupportList, L1 = apriori(dataSet,)
    s_type = frozenset([steeltype])
    relat_type = [frozenset(steeltype)]
    for l1 in L1:
        if s_type.issubset(l1):
            relat_type.append(l1-s_type)
    del(relat_type[0])
    print(steeltype, '相关钢种的个数为', len(relat_type))
    print(relat_type)
    return relat_type


# -----------------------------------------------m_lstm-----------------------------------------------------------------
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = pd.DataFrame(data)
    cols, names = list(), list()
    # input sequence (t-n, ... t-1)
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]
    # forecast sequence (t, t+1, ... t+n)
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j+1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]
    print(names)
    # put it all together
    agg = pd.concat(cols, axis=1)
    agg.columns = names
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg


def get_lstm_dataset(stl_type, url=new_url):
    dataset = pd.read_csv(url, header=0, index_col=0)
    b_len, b_list = dp.get_relalted_steel(stl_type)
    print('b_list', b_list)
    b = dataset[b_list]
    b = b[6:]
    b_values = b.values
    b_values = b_values.astype('float32')
    b_data = series_to_supervised(b_values, 1, 1)
    b_data.drop(b_data.columns[range(b_len + 1, 2 * b_len)], axis=1, inplace=True)
    # return b_data, scaler
    return b_data


def load_split_dataset(b_data):  # 'A16050JJNON'
    values = b_data.values
    v_len = len(values)
    n_train_mons = int(0.9 * v_len)
    train = values[:n_train_mons, :]
    test = values[n_train_mons:, :]

    # split into input and outputs
    train_X, train_y = train[:, :-1], train[:, -1]  # (samples, features)
    test_X, test_y = test[:, :-1], test[:, -1]  # (samples, features)
    # reshape input to be 3D [samples, timesteps, features]
    train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
    test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
    print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)
    return train_X, train_y, test_X, test_y


def tb_visualization():
    log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    return keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)


def model_design(train_X, train_y, test_X, test_y):
    # design network
    model = Sequential()
    model.add(LSTM(units, input_shape=(train_X.shape[1], train_X.shape[2]), activation='relu'))  # input_shape:(time_steps=1, features)
    model.add(Dense(1))
    model.compile(loss='mse', optimizer='adam')
    # fit network
    history = model.fit(train_X, train_y, epochs=epochs, batch_size=batch_size, validation_data=(test_X, test_y),
                        verbose=2, shuffle=False, callbacks=[tb_visualization()])
    # Param个数： 4*m*n+4*m*m+4*m*1  n为输入向量的维度，即输入特征个数，m为隐藏层的维度，即units个数
    print(model.summary())
    return model, history


def get_weights(model):
    i = 0
    for weight in model.get_weights():  # weights from layer
        print(i)
        i = i + 1
        print(weight.shape)
        print(weight)


def plot_model_history(history):
    # plot history
    pyplot.plot(history.history['loss'], label='train')
    pyplot.plot(history.history['val_loss'], label='test')
    pyplot.legend()
    pyplot.savefig('Image/train_test_loss.jpeg')
    pyplot.show()
    pyplot.close()


def make_prediction(test_X, model):
    # make a prediction
    # yhat是预测结果
    yhat = model.predict(test_X)
    return yhat


def plot_model_prediction(test_y, yhat):
    inv_yhat = clip(yhat, 0, max(yhat), out=yhat)
    print('inv_yhat', inv_yhat.shape)
    # invert scaling for actual
    test_y = test_y.reshape((len(test_y), 1))
    inv_y = test_y
    print('inv_y', inv_y.shape)
    # calculate RMSE
    rmse = sqrt(mean_squared_error(inv_y, inv_yhat))
    print('Test RMSE:%.3f' % rmse)
    pyplot.plot(inv_y, label='y')
    pyplot.plot(inv_yhat, label='yhat')
    pyplot.legend()
    pyplot.savefig('Image/mlstm_y_yhat.jpeg')
    pyplot.show()
    pyplot.close()


if __name__ == '__main__':
    # multi-variate time series prediction(apriori + mlstm)
    b_data = get_lstm_dataset(aimed_stl)
    train_X, train_y, test_X, test_y = load_split_dataset(b_data)
    model, history = model_design(train_X, train_y, test_X, test_y)
    get_weights(model)
    plot_model_history(history)
    yhat = make_prediction(test_X, model)
    plot_model_prediction(test_y, yhat)
